package com.k.kpp.web.easyexcel2.handler;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.util.PropertyPlaceholderHelper;

import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.stream.Collectors;

public class HeaderFormatHandler implements CellWriteHandler {

    PropertyPlaceholderHelper placeholderHelper = new PropertyPlaceholderHelper("${", "}");
    private final Properties properties;

    public HeaderFormatHandler(Properties prop) {
        this.properties = prop;
    }

    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
        if (isHead) {
            List<String> originHeadNames = head.getHeadNameList();
            if (CollectionUtils.isNotEmpty(originHeadNames)) {
                List<String> newHeadNames = originHeadNames.stream().
                        map(a -> resolveHeadName(a, properties)
                        ).collect(Collectors.toList());
                head.setHeadNameList(newHeadNames);
            }
        }
    }

    private String resolveHeadName(String headName, Properties prop) {
        if (StringUtils.isNotBlank(headName)) {
            if (Objects.nonNull(prop)) {
                headName = placeholderHelper.replacePlaceholders(headName, prop);
            }
        }
        return headName;
    }
}
